File Input and Output in C

A file is a sequence of bytes on the disk which holds some data. The files are store on the permanent storage which is hardisk.

In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

The C language provides a number of functions to perform operations on the file. They are

  • fopen() -> Function to create a new file or open an existing file.
  • fclose() -> Function to closes a file.
  • getc() -> Function to read a character from a file.
  • putc() -> Function to write a character to a file.
  • fscanf() -> Function to read a set of data from a file.
  • fprintf() -> Function to write a set of data to a file.
  • getw() -> Function to read an integer from a file.
  • putw() -> Function to write an integer to a file.
  • fseek() -> Function to set the file pointer to desired point.
  • ftell() -> Function to give current position in the file.
  • rewind() -> Function to set the position to the begining point.

Opening a file

C provides fopen() function to open a file. These functions are available in stdio.h header file.

Syntax for opening a file

fp = fopen("fileopen","mode");

Example

fopen("E:\\cprogram\\sample.txt","w");

The first parameter in fopen() function is to open a file. It contains 2 arguments, the first argument is the filename and the second parameter is the mode in which the file should be opened.

Here the mode is w, which means to write mode.

Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
w Open for writing. If the file exists, its contents are overwritten.
wb Open for writing in binary mode. If the file exists, its contents are overwritten.
a Open for append. Data is added to the end of the file.
ab Open for append in binary mode. Data is added to the end of the file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen() returns NULL.
w+ Open for both reading and writing. If the file exists, its contents are overwritten.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents are overwritten.
a+ Open for both reading and appending. If the file does not exist, it will be created.
ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.

Closing a file

Once you open a file, then we should close the file after the file operation. Closing the file can be done using fclose() function.

Example

fclose(fp);

where, fp is the file pointer associated with the file.

Reading and writing a file

For reading and writing a file, we can use fscanf() and fprintf() functions. The fprintf() funciton is responsible for writing to a file and fscanf() function is used to read from a file.

Example 1

#include<stdio.h>

struct employee
{
    char name[30];
    int age;
};

void main()
{
    struct employee emp;
    FILE *fr,*fw;
    fr = fopen("sample1.txt", "a");
    fw = fopen("sample2.txt", "r");
    printf("Enter Name and Age:");
    scanf("%s %d", emp.name, &emp.age);
    fprintf(fr,"%s %d", emp.name, emp.age);
    fclose(fr);
    do
    {
        fscanf(fw,"%s %d", emp.name, emp.age);
        printf("%s %d", emp.name, emp.age);
    }
    while(!feof(fw));
}

Example 2

#include <stdio.h>
int main()
{
   char name[50];
   int marks, i, num;

   printf("Enter number of students: ");
   scanf("%d", &num);

   FILE *fptr;
   fptr = (fopen("C:\\student.txt", "w"));
   if(fptr == NULL)
   {
       printf("Error!");
       exit(1);
   }

   for(i = 0; i < num; ++i)
   {
      printf("For student%d\nEnter name: ", i+1);
      scanf("%s", name);

      printf("Enter marks: ");
      scanf("%d", &marks);

      fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
   }

   fclose(fptr);
   return 0;
}

Reading and writing using getc() and putc() function

The getc() and putc() are the functions which are used to read and write individual characters to a file.

Example

#include<stdio.h>

int main()
{
    FILE *fr, *fw;
    char ch;
    fr = fopen("one.txt", "w");
    printf("Enter your data...");
    while( (ch = getchar()) != EOF) {
        putc(ch, fr);
    }
    fclose(fr);
    fw = fopen("one.txt", "r");
 
    while( (ch = getc(fr)! = EOF)
    printf("%c",ch);
    
    // closing the file pointer
    fclose(fw);
    
    return 0;
}

In the above program, first we open the file in read mode and then we get input from the user character by character and write it to the file character by character using putc() function. Finally, we will close the file pointer.

Similarly, we will read character by character using getc() function and write it to the terminal.

Finally, we will close the file pointer using fclose() function.

Read and Write Binary File

The binary files are the files in which data is stored in binary format. We use fread() and fwrite() functions to read and write a binary file.

Syntax

fwrite(data-element-to-be-written, size_of_elements, number_of_elements, pointer-to-file);

Example

const char *message = "Welcome to Readersbuddy";   
FILE *fptr= fopen("sample.txt", "wb");   
if (fptr) 
{     
    fwrite(message, sizeof(char), strlen(message), fptr);     
    fclose(fptr);   
}

Getting file data using fseek() function.

The fseek() function is used to move file pointer associated with a given file to a specific position in the file.

Syntax

int fseek(FILE *pointer, long int offset, int position);

where

pointer: pointer to a FILE object.

offset: number of bytes to offset from position

position: position from where offset is added.

The position defines the point with respect to which the file pointer needs to be moved. It has three values:

SEEK_END - Denotes the end of file.

SEEK_SET - Denotes the start of the file.

SEEK_CUR - Denotes file pointer's current position.

Example

#include <stdio.h>
  
int main()
{
    FILE *fptr;
    fptr = fopen("sample.txt", "r");
      
    // Moving pointer to end
    fseek(fptr, 0, SEEK_END);
      
    // Printing position of pointer
    printf("%ld", ftell(fptr));
  
    return 0;
}

Output

101

Most Read